package main

import (
  "sdl"
  //"sdl/ttf"
  "log"
)

type Container struct {
  Base

  windows [10]*Window
  windowsi int
}

func NewContainer(x, y, w, h int) *Container {
  container := new(Container)
  container.x = x
  container.y = y
  container.w = w
  container.h = h
  container.windowsi = 0
  return container
}

func (d *Container) add(window Window) {
  log.Stderr("Container: Added window", &d, d.windowsi)
  d.windows[d.windowsi] = &window
  d.windowsi++
  d.layout()
}

func (d *Container) getWidgetAt(x int, y int) Window { 

  for i, win := range d.windows {
    if i >= d.windowsi { break } // XXX, HACK!
    //log.Stderr("Container: Draw", i)
    wid := win.getWidgetAt(x, y)
    if wid != nil {
      return *win
    }
  }

  if x >= d.x && x <= d.x + d.w && y >= d.y && y <= d.y + d.h {
    return d
  }
  return nil
}

func (d *Container) draw(surface *sdl.Surface) {
  
  // Draw 
  if (Window)(d) == GetActiveWindow() {
    surface.FillRect(&sdl.Rect{int16(d.x) - 1, int16(d.y) - 1, uint16(d.w) + 2, uint16(d.h) + 2}, 0xff0000)
  }
  surface.FillRect(&sdl.Rect{int16(d.x), int16(d.y), uint16(d.w), uint16(d.h)}, 0x550000);
  
  // Draw other
  for i, win := range d.windows {
    if i >= d.windowsi { break } // XXX, HACK!
    //log.Stderr("Container: Draw", i)
    win.draw(surface)
  }
}

func (d *Container) layout() {
  log.Stderr("Container: Layout")
  const padding int = 10
  x := d.x + padding
  y := d.y + padding
  log.Stderr("First widget at ", x, y)
  for i, win := range d.windows {
    if i >= d.windowsi { break } // XXX, HACK!
    win.setX(x)
    win.setY(y)
    log.Stderr("Window ", i, win.getX(), win.getY())
    y += win.getHeight() + padding
  }
}
